package com.gobang.gobang;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Optional;

public class RoomListController {
    @FXML private TextField nameField;
    @FXML private Button createRoomButton;
    @FXML private TableView<RoomInfo> roomTable;
    @FXML private TableColumn<RoomInfo, String> roomNameColumn;
    @FXML private TableColumn<RoomInfo, String> player1Column;
    @FXML private TableColumn<RoomInfo, String> player2Column;
    @FXML private TableColumn<RoomInfo, String> statusColumn;
    @FXML private Label statusLabel;
    @FXML private TextField serverIpField;  // 添加IP地址输入框
    @FXML private Button connectButton;

    private NetworkManager networkManager;
    
    @FXML
    public void initialize() {
        // 设置表格列的数据绑定
        roomNameColumn.setCellValueFactory(new PropertyValueFactory<>("roomName"));
        player1Column.setCellValueFactory(new PropertyValueFactory<>("player1Name"));
        player2Column.setCellValueFactory(new PropertyValueFactory<>("player2Name"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
        
        // 初始状态下禁用创建房间按钮，直到输入用户名
        createRoomButton.setDisable(true);
        
        // 监听用户名输入
        nameField.textProperty().addListener((obs, old, newValue) -> {
            if (!newValue.trim().isEmpty() && networkManager != null) {
                // 当用户输入名字时，发送登录消息
                networkManager.sendMessage("LOGIN|" + newValue.trim());
                createRoomButton.setDisable(false);
                // 请求房间列表
                networkManager.sendMessage("GET_ROOMS");
            } else {
                createRoomButton.setDisable(true);
            }
        });
        
        // 添加表格双击事件
        roomTable.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                RoomInfo selectedRoom = roomTable.getSelectionModel().getSelectedItem();
                if (selectedRoom != null && !selectedRoom.isFull() && !selectedRoom.getStatus().equals("对局中")) {
                    joinRoom(selectedRoom.getRoomId());
                }
            }
        });
    }
    
    @FXML
    public void handleConnect() {
        String serverIp = serverIpField.getText().trim();
        if (serverIp.isEmpty()) {
            showAlert("错误", "请输入服务器IP地址");
            return;
        }
        
        // 禁用连接按钮，直到连接成功或失败
        connectButton.setDisable(true);
        statusLabel.setText("正在连接...");
        
        // 连接到服务器
        networkManager = new NetworkManager(serverIp, GobangServer.PORT, this);
        networkManager.connect();
    }
    
    // 修改连接成功的处理
    public void onConnectionSuccess() {
        Platform.runLater(() -> {
            statusLabel.setText("连接成功");
            nameField.setDisable(false);  // 启用用户名输入
            connectButton.setDisable(false);  // 允许重新连接
            serverIpField.setDisable(false);  // 允许修改IP
            
            // 如果已经有用户名，则发送登录消息
            String userName = nameField.getText().trim();
            if (!userName.isEmpty()) {
                networkManager.sendMessage("LOGIN|" + userName);
                createRoomButton.setDisable(false);
                networkManager.sendMessage("GET_ROOMS");
            }
        });
    }
    
    // 修改连接失败的处理
    public void onConnectionFailed(String error) {
        Platform.runLater(() -> {
            statusLabel.setText("连接失败: " + error);
            connectButton.setDisable(false);
            serverIpField.setDisable(false);
        });
    }
    
    @FXML
    private void handleCreateRoom() {
        String playerName = nameField.getText().trim();
        if (playerName.isEmpty()) {
            showAlert("错误", "请输入用户名");
            return;
        }
        
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("创建房间");
        dialog.setHeaderText(null);
        dialog.setContentText("请输入房间名称：");
        
        Optional<String> result = dialog.showAndWait();
        result.ifPresent(roomName -> {
            networkManager.sendMessage("CREATE_ROOM|" + roomName);
            openGameWindow();
        });
    }
    
    private void joinRoom(String roomId) {
        String playerName = nameField.getText().trim();
        if (playerName.isEmpty()) {
            showAlert("错误", "请输入用户名");
            return;
        }
        
        networkManager.sendMessage("JOIN_ROOM|" + roomId);
        openGameWindow();
    }
    
    private void openGameWindow() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("gobang-view.fxml"));
            Scene gameScene = new Scene(loader.load());
            GobangController controller = loader.getController();
            
            // 传递网络管理器到游戏控制器
            controller.setNetworkManager(networkManager);
            
            Stage gameStage = new Stage();
            gameStage.setTitle("五子棋");
            gameStage.setScene(gameScene);
            gameStage.show();
            
            // 关闭房间列表窗口
            ((Stage) nameField.getScene().getWindow()).close();
            
        } catch (IOException e) {
            showAlert("错误", "无法打开游戏窗口");
        }
    }
    
    public void updateRoomList(String roomListData) {
        Platform.runLater(() -> {
            roomTable.getItems().clear();
            String[] rooms = roomListData.split(";");
            for (String room : rooms) {
                if (!room.isEmpty()) {
                    String[] data = room.split(",");
                    roomTable.getItems().add(new RoomInfo(
                        data[0], // roomId
                        data[1], // roomName
                        data[2], // player1Name
                        data[3], // player2Name
                        data[4]  // status
                    ));
                }
            }
        });
    }
    
    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public void setStatusText(String text) {
        Platform.runLater(() -> statusLabel.setText(text));
    }

    @FXML
    private void handleRefresh() {
        if (networkManager != null) {
            networkManager.sendMessage("GET_ROOMS");
        }
    }
} 